 import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/account/iview/below_user_deposit_score_page_ivew.dart';
import 'package:flutter_deer/account/models/user_score_deposit_entity.dart';
import 'package:flutter_deer/account/presenter/below_user_deposit_score_presenter.dart';
import 'package:flutter_deer/account/provider/below_user_deposit_score_page_provider.dart';
import 'package:flutter_deer/account/widgets/rise_number_text.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/dimens.dart';
import 'package:flutter_deer/res/gaps.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class BelowUserDepositScorePage extends StatefulWidget {

  const BelowUserDepositScorePage({super.key});

  @override
  _BelowUserDepositScorePageState createState() => _BelowUserDepositScorePageState();
}

class _BelowUserDepositScorePageState extends State<BelowUserDepositScorePage> with BasePageMixin<BelowUserDepositScorePage, PowerPresenter>, AutomaticKeepAliveClientMixin<BelowUserDepositScorePage> implements BelowUserDepositScorePageIMvpView {

  final ScrollController _scrollController = ScrollController();

  BelowUserDepositScorePageProvider provider = BelowUserDepositScorePageProvider();

  bool get wantKeepAlive => false;

  late BelowUserDepositScorePresenter belowUserDepositScorePresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(
        this);
    belowUserDepositScorePresenter = new BelowUserDepositScorePresenter();
    powerPresenter.requestPresenter([belowUserDepositScorePresenter]);
    return powerPresenter;
  }

  @override
  void setBelowUserDepositScorePage(BelowUserScoreDepositPageEntity? pageEntity){
    provider.setBelowUserDepositScorePage(pageEntity);
  }

  @override
  void setStatistics(BelowUserScoreDepositStatisticsEntity? entity){
    provider.setStatistics(entity);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    if(mounted){
      _onRefresh();
    }
  }

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1),()=>{belowUserDepositScorePresenter.getDeposotScoreList()});
  }

  Future<dynamic> _loadMore() async {
    belowUserDepositScorePresenter.getMoreDepositScoreList(provider.currentPage!+1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: MyAppBar(centerTitle: '${DeerLocalizations.of(context)!.rechargeRecord.nullSafe}'),
        body: ChangeNotifierProvider<BelowUserDepositScorePageProvider>(
        create: (_) => provider,
    child:  Consumer<BelowUserDepositScorePageProvider>(
    builder: (_,provider,child){
      if(provider.stateType==StateType.loading||provider.statisticsStateType==StateType.loading){
        return StateLayout(type: StateType.loading);
      }
          return DeerListView(
            itemCount: provider.list!.length+1,
            stateType: provider.stateType!,
            onRefresh: _onRefresh,
            loadMore: _loadMore,
            hasMore: provider.hasMore!,
            itemBuilder: (_, index) {
              if(index==0){
                return _buildCard(provider,provider.totalScore,provider.totalTimes);
              }
              BelowUserScoreDepositEntity item = provider.list!.elementAt(index-1);
              return Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10.0,vertical: 5),
                child: MyCard(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 5),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Gaps.vGap5,
                          Row(
                            children: [
                              CircleAvatar(radius: 24.0,backgroundColor: Colors.transparent,backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${item!.avatar}', holderImg: 'shop/tx')),
                              Gaps.hGap8,
                              Text('${DeerLocalizations.of(context)!.playerAccount.nullSafe}:${item!.accountId}')
                            ]
                          ),
                          Gaps.vGap8,
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text('${DeerLocalizations.of(context)!.rechargeAmount.nullSafe}:${NumberFormat.decimalPattern('en_us').format(item!.score)}'),
                                Text('${DeerLocalizations.of(context)!.rechargeTime.nullSafe}:${item!.updateTime}'),
                              ]
                          ),
                          Gaps.vGap5
                        ]
                    )
                  )
                )
              );
            }
          );
    }
    )));
  }

  Widget _buildCard(BelowUserDepositScorePageProvider provider,double? totalScore,int? totalTimes) {
    return AspectRatio(
        aspectRatio: 2.55,
        child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 6.0),
            padding: const EdgeInsets.all(6.0),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: ImageUtils.getAssetImage('account/bg'),
                fit: BoxFit.fill,
              ),
            ),
            child: provider.statisticsStateType==StateType.loading?Row(
                children: <Widget>[
                  _DepositStatistics(title: '${DeerLocalizations.of(context)!.accumulatedRecharge.nullSafe}', count: '0.00',countFormat:'double'),
                  _DepositStatistics(title: '${DeerLocalizations.of(context)!.rechargeTimes.nullSafe}', count: '0',countFormat:'int'),
                ]
            ):Row(
                children: <Widget>[
                  _DepositStatistics(title: '${DeerLocalizations.of(context)!.accumulatedRecharge.nullSafe}', count: '${totalScore}',countFormat:'double'),
                  _DepositStatistics(title: '${DeerLocalizations.of(context)!.rechargeTimes.nullSafe}', count: '${totalTimes}',countFormat:'int'),
                ]
            )
        )
    );
  }

}

class _DepositStatistics extends StatelessWidget {

  const _DepositStatistics({
    required this.title,
    required this.count,
    required this.countFormat,
    this.alignment,
    this.moneyTextStyle
  });

  final String title;
  final String count;
  final String countFormat;
  final MainAxisAlignment? alignment;
  final TextStyle? moneyTextStyle;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: MergeSemantics(
        child: Column(
          mainAxisAlignment: alignment ?? MainAxisAlignment.center,
          children: <Widget>[
            /// 横向撑开Column，扩大语义区域
            const SizedBox(width: double.infinity),
            Text(title, style: const TextStyle(color: Colours.text_disabled, fontSize: Dimens.font_sp14)),
            Gaps.vGap8,
            countFormat=='double'?
            RiseNumberText(
                NumUtil.getDoubleByValueStr(count) ?? 0,
                style: moneyTextStyle ?? const TextStyle(
                    color: Colours.text_disabled,
                    fontSize: Dimens.font_sp14,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'RobotoThin'
                )
            ):Text(count,style: moneyTextStyle ?? const TextStyle(
                color: Colours.text_disabled,
                fontSize: Dimens.font_sp14,
                fontWeight: FontWeight.bold,
                fontFamily: 'RobotoThin'
            )
            )
          ],
        ),
      ),
    );
  }
}